package com.example.library

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * 全局的viewmodel,可以跨页面使用
 */
class GlobalViewModel : ViewModelStoreOwner {
    private var viewModelStore: ViewModelStore? = null

    companion object {
        private val instance: GlobalViewModel by lazy {
            GlobalViewModel()
        }

        fun get() = instance
    }

    fun <T : ViewModel> getViewModel(clazz: Class<T>): T {
        return ViewModelProvider(this).get(clazz)
    }

    override fun getViewModelStore(): ViewModelStore {
        if (viewModelStore == null) {
            viewModelStore = ViewModelStore()
        }
        return viewModelStore!!
    }
}